package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.MemberDao;
import com.atguigu.gulimall.product.entity.Member;
import com.atguigu.gulimall.product.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, Member> implements MemberService {


    @Override
    public boolean saveMember(Member member) {
        if(null == member){
            return  false;
        }
        if(StringUtils.isEmpty(member.getUsername()) || StringUtils.isEmpty(member.getPassword())){
            return  false;
        }
        int count = this.baseMapper.selectCount(new QueryWrapper<Member>().eq("username", member.getUsername()));
        if(count > 0){
            return  false;
        }
        member.setId(1L);
        member.setDelFlag(false);
        super.save(member);
        return true;
    }

    @Override
    public boolean updateMember(Member member) {
        if(null == member || member.getId() == null){
            return  false;
        }
        if(StringUtils.isEmpty(member.getUsername()) || StringUtils.isEmpty(member.getPassword())){
            return  false;
        }
        Member pMember = this.baseMapper.selectOne(new QueryWrapper<Member>().eq("username", member.getUsername()));
        if(pMember != null && !pMember.getId().equals(member.getId())){
            return  false;
        }
        super.updateById(member);
        return true;
    }

    @Override
    public List<Member> findPage(Integer pageNumber, Integer pageSize, String keyword) {
        List<Member> members = this.baseMapper.selectList(new QueryWrapper<Member>().eq("del_flag", 0));
        return members;
    }

    @Override
    public Member findById(Long id) {
        if(null == id || id <= 0){
            return  null;
        }
        return super.getById(id);
    }

    @Override
    public boolean deleteMember(List<Long> ids) {
        if(null == ids || ids.size() == 0){
            return  false;
        }
        //真删除 - 物理删除
        // super.removeByIds(ids);
        // 假删除 - 逻辑删除
        List<Member> members = Lists.newArrayList();
        for(Long id : ids){
            Member member = new Member();
            member.setId(id);
            member.setDelFlag(true);
            members.add(member);
        }
        super.saveOrUpdateBatch(members);
        return false;
    }
}
